package com.rapida.plugin;

import android.util.SparseArray;

import java.util.ArrayList;
import java.util.List;

public class PluginImpl implements IPlugin {
	private final SparseArray<PluginAgent> mRegisteredPluginAgents = new SparseArray<PluginAgent>(2);

	public PluginImpl() {
	}

	public int nextId() {
		if (mRegisteredPluginAgents.size() == 0) {
			return 0;
		}
		return mRegisteredPluginAgents.size() + 1;
	}

	@Override
	public void registerPlugin(PluginAgent agent) {
		if (agent == null) {
			throw new NullPointerException("Registering a null PluginAgent.");
		}
		final int pluginId = agent.getPluginId();
		if (pluginId == PLUGIN_INDEX_NONE) {
			throw new IllegalArgumentException("PluginManager: The Plugin ID can not be " + "PLUGIN_INDEX_NONE");
		}
		if (mRegisteredPluginAgents.get(pluginId) != null) {
			throw new IllegalArgumentException("Plugin ID is registered already:" + pluginId);
		}
		mRegisteredPluginAgents.put(pluginId, agent);
	}

	@Override
	public boolean unregisterPlugin(int PluginId) {
		if (mRegisteredPluginAgents.get(PluginId) == null) {
			return false;
		}
		mRegisteredPluginAgents.delete(PluginId);
		return true;
	}

	@Override
	public List<PluginAgent> getRegisteredPluginAgents() {
		List<PluginAgent> agents = new ArrayList<PluginAgent>();
		for (int i = 0; i < mRegisteredPluginAgents.size(); i++) {
			agents.add(mRegisteredPluginAgents.valueAt(i));
		}
		return agents;
	}

	@Override
	public List<Integer> getSupportedModeIndexList() {
		List<Integer> modeIndexList = new ArrayList<Integer>();
		for (int i = 0; i < mRegisteredPluginAgents.size(); i++) {
			modeIndexList.add(mRegisteredPluginAgents.keyAt(i));
		}
		return modeIndexList;
	}

	@Override
	public PluginAgent getPluginAgent(int PluginId) {
		return mRegisteredPluginAgents.get(PluginId);
	}
}
